// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.formatStr = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var PN = location.pathname.split(/\//)[1];
var webPath = '/' + PN + '/';
var baseServices_restfulUrl = webPath;


function GetRequest() {
    var url = window.location.href;
    //var theRequest = new Object();
    if (url.indexOf("#/") != -1) {
        var str = url.split("#/");
        str = str[1];
        if (str.indexOf("/") != -1) {
            strs = str.split("/");
        } else {
            strs = str;
        }
        /*for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
         }*/
        //console.log("strs:"+strs);
    }
    //return theRequest;
}

/**
 *
 * @param id
 * @returns {Object}
 */
function getObjWidthHeight(id) {
    var ret = {};
    var obj = document.getElementById(id);
    ret["width"] = obj.offsetWidth;
    ret["height"] = obj.offsetHeight;
    return ret;
}

// sessionStorage 存储Json对象
function getSessionJson(key) {
    isEmpty(sessionStorage.getItem(key)) ? sessionStorage.setItem(key, JSON.stringify({})) : '';
    return JSON.parse(sessionStorage.getItem(key));
}

function setSessionJson(key, json) {
    sessionStorage.setItem(key, JSON.stringify(json));
    return sessionStorage.getItem(key);
}

function removeSession(key) {
    if (!isEmpty(key)) sessionStorage.removeItem(key);
}

/**
 * String去除前后空格
 * */
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
};

/**
 * [判空]
 * @author liuxiaotang
 * @param  {String |Object |Array |Number}  para [null]
 * @return {Boolean}      [true | false]
 */
function isEmpty(para) {
    if (typeof(para) === "undefined") {
        return true;
    } else if (typeof(para) === "string") {
        return (para.trim() === '');
    } else if (para instanceof Array) {
        return (para.length === 0);
    } else if (typeof(para) === "object" && !(para instanceof Array)) {
        var para_name;
        for (para_name in para) {
            return false;
        }
        return true;
    } else if (typeof(para) === "number") {
        isEmpty(para + '');
    }
}

/**
 * [onlyNum input输入框只能输数字]
 * @author liuxiaotang
 * @param  {Object} event [NOT NULL，不传会导致不兼容firefox和ie]
 * @param  {Number} length [小数点位数，为空时默认没有小数]
 * @return {Boolean}       [description]
 *
 *  example:
 *  <input type="text" onkeydown="return onlyNum(event,2);" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]|[(~！@#￥%…&*（）—=·+{}：“《》？、。，‘’；】【\-)+]/g,'')"
 onpaste="return false" ondrop="return false" required>
 *
 *  onkeydown不加return会导致不兼容firefox/ie
 *
 */
function onlyNum(event, length) {
    var input = event.target.value;
    var point = (length === undefined || /\./.exec(input)) ? 0 : 1;

    var e = (event) ? event : ((window.event) ? window.event : "");//兼容IE和Firefox获得keyBoardEvent对象
    var key = e.keyCode ? e.keyCode : e.which;//兼容IE和Firefox获得keyBoardEvent对象的键值

    if (e.shiftKey) { //shift + any key
        e.returnValue = false;
        return false;
    }

    if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || (point && (key == 190 || key == 110))) { // 数字键
    } else if (key == 8 || key == 9 || key == 13 || (key >= 37 && key <= 40 || key == 46)) {//功能键
    } else {
        e.returnValue = false;
        return false;
    }

    if (input.indexOf('.') != -1) {
        var decimal = input.substring(input.indexOf('.') + 1);
        if (decimal.length >= length) {
            if (key == 8 || key == 9 || key == 13 || (key >= 37 && key <= 40 || key == 46)) {//功能键
            } else {
                e.returnValue = false;
                return false;
            }
        }
    }
}

/**
 * 检查手机号是否正确
 * @param phone
 * @returns {boolean}
 */
function checkPhone(phone) {
    return /^1[345789]\d{9}$/.test(phone);
}

/**
 * 移除数组中匹配的元素
 *
 * a=['001','002','003'];
 * a.removeArrItem['002'];//==>['001','003'];
 *
 * @param item
 */
Array.prototype.removeItem = function (item) {
    var idx = this.indexOf(item);
    idx !== -1 ? this.splice(idx, 1) : console.log('数组[' + this + ']中没有匹配"' + item + '"的参数');
};
/**
 * 数组移除 null 元素
 */
Array.prototype.removeNullObj = function () {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === null) {
            this.splice(i, 1);
            i--;
        }
    }
};

/**
 * 数组去重
 */
Array.prototype.removeIdentical = function () {
    var tempArr = [];
    for (var v in this) {
        if (this.hasOwnProperty(v)) {
            if (!tempArr[this[v]]) {
                tempArr[this[v]] = this[v];
            } else {
                this.splice(v, 1);
            }
        }
    }
};

/*cookies*/
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            c_end == -1 ? c_end = document.cookie.length : '';
            return decodeURI(document.cookie.substring(c_start, c_end));
        }
    }
    return ""
}

//
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + encodeURI(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function removeCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

/**
 * json格式的string字符串格式化输出
 * @param {String} txt
 * @param {Boolean} compress 是否为压缩模式
 * @returns {string|Boolean}
 */
function beautyJsonStr(txt, compress) {
    var indentChar = '    ';
    if (/^\s*$/.test(txt)) {
        alert('数据为空,无法格式化! ');
        return false;
    }
    try {
        var data = eval('(' + txt + ')');
    }
    catch (e) {
        alert('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err');
        return false;
    }
    var draw = [], last = false, This = this, line = compress ? '' : '\n', nodeCount = 0, maxDepth = 0;

    var notify = function (name, value, isLast, indent/*缩进*/, formObj) {
        nodeCount++;
        /*节点计数*/
        for (var i = 0, tab = ''; i < indent; i++) tab += indentChar;
        /* 缩进HTML */
        tab = compress ? '' : tab;
        /*压缩模式忽略缩进*/
        maxDepth = ++indent;
        /*缩进递增并记录*/
        if (value && value.constructor == Array) {/*处理数组*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '[' + line);
            /*缩进'[' 然后换行*/
            for (var i = 0; i < value.length; i++)
                notify(i, value[i], i == value.length - 1, indent, false);
            draw.push(tab + ']' + (isLast ? line : (',' + line)));
            /*缩进']'换行,若非尾元素则添加逗号*/
        } else if (value && typeof value == 'object') {/*处理对象*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '{' + line);
            /*缩进'{' 然后换行*/
            var len = 0, i = 0;
            for (var key in value) len++;
            for (var key in value) notify(key, value[key], ++i == len, indent, true);
            draw.push(tab + '}' + (isLast ? line : (',' + line)));
            /*缩进'}'换行,若非尾元素则添加逗号*/
        } else {
            if (typeof value == 'string') value = '"' + value + '"';
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + value + (isLast ? '' : ',') + line);
        }
    };
    var isLast = true, indent = 0;
    notify('', data, isLast, indent, false);
    return draw.join('');
}

/**
 * 解析如url的查询字符串为 js对象
 * @param {String} queryString example：closeSocket=fromUser&arg2=off&arg3=1
 * @returns {Object}
 */
function parseQueryStringToObj(queryString) {
    var argArray = queryString.replace("?", "").split("&");
    var argObj = {};
    for (var i = 0; i < argArray.length; i++) {
        if (argArray[i].indexOf("=") !== -1) {
            var tempArray = argArray[i].split("=");
            argObj[tempArray[0]] = tempArray[1];
        }
    }
    return argObj;
}

function showLoader() {
    document.getElementById('showLoader').style.display = 'block';
}

function hideLoader() {
    document.getElementById('showLoader').style.display = 'none';
}

/**
 * 生成UUID
 *
 * // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
 * // by minimizing calls to random()
 * @returns {string}
 */
Math.uuid = function () {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
        uuid = new Array(32),
        rnd = 0, r;
    for (var i = 0; i < 32; i++) {
        if (i === 12) {
            uuid[i] = '4';
        } else {
            if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
            r = rnd & 0xf;
            rnd = rnd >> 4;
            uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
        }
    }
    return uuid.join('');
};

(function checkBrowser() {
    // Chrome
    // "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36"
    // FireFox
    // "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
    // Edge
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"

    // IE
    // 11 "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko"
    // 10 "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"
    //  9 "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
    //  8 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"
    //  7 "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"

    // 360 safe browser
    // "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"

    var userAgent = navigator.userAgent.toLowerCase(), version = '', fuckOff = false;
    if (userAgent.indexOf('edge') > -1) {
    } else if (userAgent.indexOf("chrome") > -1) {
        version = userAgent.match(/chrome\/[\d\.]+/)[0].split('/')[1];
        fuckOff = parseFloat(version) < 42
    } else if (userAgent.indexOf("Firefox") > -1) {
        version = userAgent.match(/Firefox\/[\d\.]+/)[0].split('/')[1];
        fuckOff = parseFloat(version) < 46
    } else if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("msie") > -1) {
        version = userAgent.match(/msie\s[\d\.]+/)[0].split(' ')[1];
        fuckOff = parseFloat(version) < 10
    }
    fuckOff && (location.href = '/' + PN + '/updateBrowser.html')
})();